<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Constants\ErrorCode;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Distributors;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;

class ChargeController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected ChargeDetail $chargeDetail;

    #[Inject]
    protected Distributors $distributors;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**套餐列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword','is_autoload','mode']);
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $data['list'] = $this->chargeOption->where(function ($query) use ($page,$info) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('content', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_autoload'] != ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            if($page['mode'] == 'normal'){
                $query->where('distributor_id','=',0);
            }else{
                $query->where('distributor_id','=',$info['id']);
            }
            $query->where('is_del',1);
        })->orderBy('sort', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','name','is_autoload','fee'])->toArray();
        $data['total']= $this->chargeOption->where(function ($query) use ($page,$info) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['is_autoload'] != ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            if($page['mode'] == 'normal'){
                $query->where('distributor_id','=',0);
            }else{
                $query->where('distributor_id','=',$info['id']);
            }
            $query->where('is_del',1);
        })->count();
        foreach($data['list'] as $k => $v){
            $data['list'][$k]['power_children'] = ChargeDetail::where('charge_option_id',$v['id'])
            ->where('type',ChargeDetail::POWER_TYPE)
            ->orderBy('sort','desc')->get(['id','minutes','min_power','max_power','charge_option_id'])->toArray();
            $data['list'][$k]['time_children'] = ChargeDetail::where('charge_option_id',$v['id'])
            ->where('type',ChargeDetail::TIME_TYPE)
            ->orderBy('sort','desc')->get(['id','minutes','fee','charge_option_id'])->toArray();
        }
        return $this->success($data);
    }


    /**创建/编辑
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['id','name','is_autoload','fee','power_children','time_children']);
        if(!$params['name']){
            return $this->error(code:1002,msg:'套餐名称不能为空');
        }
        Db::beginTransaction();
        try{
            if(isset($params['id'])){
                $charge = $this->chargeOption->where('id',$params['id'])->first();
                $charge->is_autoload = $params['is_autoload'];
                $charge->name = $params['name'];
                $charge->fee = $params['fee'];
                $charge->save();
            }else{
                $save['is_autoload'] = $params['is_autoload'];
                $save['name'] = $params['name'];
                $save['distributor_id'] = $info['id'];
                $save['fee'] = $params['fee'];
                $option = ChargeOption::create($save);
                $params['id'] = $option->id;
            }
            if(isset($params['power_children'])){
                $this->chargeDetail->where('charge_option_id',$params['id'])
                    ->where('type',ChargeDetail::POWER_TYPE)
                    ->update(['is_del'=>0]);
                $params['power_children'] = json_decode($params['power_children'],true);
                foreach($params['power_children'] as $k => $v){
                    if(isset($v['minutes']) && isset($v['min_power'])&& isset($v['max_power'])){
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::POWER_TYPE;
                        ChargeDetail::create($save);
                    }
                }
            }
            if(isset($params['time_children'])){
                $this->chargeDetail->where('charge_option_id',$params['id'])
                    ->where('type', ChargeDetail::TIME_TYPE)
                    ->update(['is_del'=>0]);
                $params['time_children'] = json_decode($params['time_children'],true);
                foreach($params['time_children'] as $k => $v){
                    if(isset($v['minutes']) && isset($v['fee']) && $v['minutes']){
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['type'] = ChargeDetail::TIME_TYPE;
                        $save['fee'] = $v['fee'];
                        $save['charge_option_id'] = $params['id'];
                        ChargeDetail::create($save);
                    }
                }
            }
            Db::commit();
            return $this->success(['charge_option_id'=>$params['id']]);
        }catch(\Exception $e){
            Db::rollBack();
            return $this->error(code:1003,msg:$e->getMessage());
        }
    }

    /**批量选择套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function batchChose(RequestInterface $request):\Psr\Http\Message\ResponseInterface{
        $params = $request->inputs(['charge_id','devices']);
        if(!$params['charge_id']){
            return $this->error(code:'1001',msg:'缺少参数charge_option_id');
        }
        $devices = json_decode($params['devices']);
        try{
            Device::whereIn('id',$devices)->update(['charge_id'=>$params['charge_id']]);
            return $this->success();
        }catch (\Exception $e){
            return $this->error(1001,'操作繁忙 请稍后重试');
        }
    }

    /**获取当前已经绑定该套餐的设备
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getChosed(RequestInterface $request):\Psr\Http\Message\ResponseInterface{
        $chargeId = $request->input('charge_id');
        if(!$chargeId){
            return $this->error(code:'1001',msg:'缺少参数charge_option_id');
        }
        $devices = Device::where('charge_id',$chargeId)
            ->get(['id']);
        $data = [];
        foreach($devices as $v){
            $data[] = $v;
        }
        return $this->success($data);
    }

    /**删除
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        Db::beginTransaction();
        try{
            $id = $request->input('id',0,'int');
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
            $this->chargeOption->where('id',$id)->update(['is_del'=>0]);
            ChargeDetail::where('charge_option_id',$id)->update(['is_del'=>0]);
            $now_charge_id =  $this->chargeOption->where('distributor_id',0)->first();
            if($now_charge_id){
                $chargeId = $now_charge_id->id;
            }else{
                $chargeId = 0;
            }
            Device::where('charge_id',$id)->update(['charge_id'=>$chargeId]);
            Db::commit();
        return $this->success();
        }catch (\Exception $e){
            Db::rollBack();
            return $this->error(code:1001,msg:'操作繁忙请稍后重试');
        }
    }

}
